// miniprogram/pages/learn/paperDetail/index.js
import {
  LearnModel
} from '../../../model/learn'
import Dialog from '@vant/weapp/dialog/dialog';
import {
  getMap
} from '../../../utils/map2'
// 用户答案
let userAnswer = getMap()
// 正确答案
let correctOption = getMap()
// 错误问题 id
let wrongQuestion = []
Page({

  /**
   * 页面的初始数据
   * type: 判断 0,单选 1,多选2
   */
  data: {
    show: false,
    type: 2,
    questionIndex: 0,
    lastQuestion: false,
    paperId: 0,
    questions: [],
    question: {},
    wrongNum: 0,
    correctPercent: 0,
    scoreTotal: 0,
    hideA: true,
    canClick: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    // console.log('onLoad',options.id)
    this.setData({
      paperId: options.id,
      title: options.title
    })
    await this.loadPaperDetail(options.id)
    // console.log('paperId', this.data.paperId)

  },
  // 查询试卷详情 paperId
  loadPaperDetail(id) {
    LearnModel.paperDetail(id).then((res) => {
      if (res && res.code == 200) {
        this.setData({
          questions: res.data
        })
        this.setData({
          question: this.data.questions[this.data.questionIndex]
        })
        if (this.isLastQuestion()) {
          this.setData({
            lastQuestion: true
          })
        }
      } else {
        console.log(res)
      }
      // console.log(this.data.questions, this.data.question)
    }).catch(e => {
      console.log(e)
    })
  },
  chooseAnswer(e) {
    let answerIndex = e.target.dataset.id
    let type = e.target.dataset.type
    console.log('optionId', answerIndex)
    // console.log(this.data.question, this.data.questionIndex)
    if (type == 2) {

    } else {
      for (let i = 0; i < this.data.question.options.length; i++) {
        if (answerIndex == i) {
          continue
        }
        this.data.question.options[i].isSelected = false
      }
    }
    this.data.question.options[answerIndex].isSelected = !this.data.question.options[answerIndex].isSelected


    this.setData({
      question: this.data.question
    })
    // console.log("chooseAnswer",this.data.question)
  },
  aqie(){
    if(this.data.hideA){
      console.log('exec A')
      this.nextQ()
    } else {
      console.log('exec B')
      this._execSetTimeout().then(() => {
        this.data.canClick = true
      })
    }
  },
  // 提交下一题时，将当前题目答案写入缓存
  nextQ() {
    // if (!this.data.canClick) {
    //   return
    // }

    this._recordUserAnswer()
    this.setData({
      hideA: false
    })
    // this.data.canClick = false
    // this._execSetTimeout().then(() => {
    //   this.data.canClick = true
    // })

  },
  _execSetTimeout() {
    return new Promise( (resolve, rejext) => {
      setTimeout(function () {
        resolve() 
        this.setData({
          hideA: true
        })
        let qn = this.data.questions.length
        this.setData({
          questionIndex: this.data.questionIndex + 1 >= qn ? qn-1 : this.data.questionIndex + 1
        })
        if (this.isLastQuestion()) {
          this.setData({
            lastQuestion: true
          })
        }
        this.setData({
          question: this.data.questions[this.data.questionIndex]
        })
      }.bind(this), 0)
    })
  },
  handPaper() {
    if (!this.data.canClick) {
      // console.log('final 不能点击')
      return
    }
    this.setData({
      hideA: false
    })
    this.data.canClick = false
    this._execSetTimeout2().then(() => {
      // console.log('final 三秒后执行')
      this.data.canClick = true
    })
  },
  _execSetTimeout2(){
    return new Promise( (resolve, rejext) => {
    setTimeout(function () {
      resolve()
      this.setData({
        hideA: true
      })
      this._recordUserAnswer()
      this._recordcorrectOption()
      // todo 拼接用户id 实体
      let data = {}
      data.userId = wx.getStorageSync('user').id;
      data.paperId = this.data.paperId

      data.correctPercent = this.data.correctPercent
      data.wrongNum = this.data.wrongNum
      data.correctNum = this.data.correctNum
      data.scoreTotal = this.data.scoreTotal
      data.title = this.data.title
      data.userAnswers = JSON.stringify(userAnswer.data)
      data.correctAnswers = JSON.stringify(correctOption.data)
      data.wrongQuestion = wrongQuestion.join(',')

      // return
      // todo 计算用户成绩
      // 弹出交卷提示
      Dialog.confirm({
          message: '确认交卷',
        })
        .then(() => {
          // on confirm
          console.log('向后台提交数据', data)
          // 弹出答题结果
          this._postUserAnswer(data)
          this.showPopup()
        })
        .catch(() => {
          // on cancel
        })

    }.bind(this), 0)
  })
  },
  _postUserAnswer(data) {
    LearnModel.postUserAnswer(data).then((res) => {
      if (res && res.code == 200) {
        console.log(res)
      } else {
        console.log(res)
      }
      // console.log(this.data.questions, this.data.question)
    }).catch(e => {
      console.log(e)
    })
  },
  _recordUserAnswer() {
    // 1. 遍历获取用户当前问题答案
    let options = this.data.question.options
    let ans = "";
    for (let i = 0; i < options.length; i++) {
      if (options[i]['isSelected']) {
        ans += (options[i]['optionId'] + ",")
      }
    }
    ans = ans.substr(0, ans.length - 1);
    // console.log(options, 'user answer', ans)
    userAnswer.put(this.data.question.questionId, ans)
    // console.log('userAnswer', userAnswer.data)
    // wx.setStorageSync('userAnswer', userAnswer)

  },
  _recordcorrectOption() {
    let questions = this.data.questions
    // console.log(questions)
    let correctNum = 0
    for (let i = 0; i < questions.length; i++) {
      // console.log("打印正确答案 和 用户答案")
      correctOption.put(questions[i].questionId, questions[i].correctOption)
      console.log(questions[i].questionId, questions[i].correctOption, userAnswer.get(questions[i].questionId), questions[i].score)
      if (questions[i].correctOption == userAnswer.get(questions[i].questionId)) {
        correctNum++
        this.data.scoreTotal += questions[i].score
        // console.log('当前总分',this.data.scoreTotal)
      } else {
        wrongQuestion.push(questions[i].questionId)
      }
    }
    this.setData({
      correctPercent: (correctNum / questions.length).toFixed(2) * 100,
      wrongNum: questions.length - correctNum,
      correctNum: correctNum
    })
  },

  showPopup() {
    this.setData({
      show: true
    });
  },

  onClose() {
    this.setData({
      show: false
    });
  },

  isLastQuestion() {
    // console.log('当前question', 'question length', this.data.questionIndex, this.data.questions.length - 1)
    return this.data.questionIndex == this.data.questions.length - 1 ? true : false
  },

  goBack() {
    this.onClose()
    wx.switchTab({
      url: '../../learn/index',
    })
  },
  tryAgain() {
    this._init()
    wx.redirectTo({
      url: `../paperDetail/index?id=${this.data.paperId}`,
    })
    // console.log(this.data.questions)
  },
  _init() {
    this.setData({
      show: false,
      questionIndex: 0,
      type: 2,
      lastQuestion: false,
    })
    userAnswer = getMap()
    // 正确答案
    correctOption = getMap()
    // 错误问题 id
    wrongQuestion = []

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // console.log('onshow paperDetail')
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})